<template>
  <s-layout title="商户支付">
    <div class="page">
      <image class="bgi" mode="aspectfit"
        src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/sjrz/20250324/6fdcef8e834bb8c2d2524e876e51d8a7.png">
      </image>

      <div class="pay_box">
        <div class="title"> 付款给：{{ state.shop_name }} </div>
        <div class="num_box">
          <div class="ico">￥</div>
          <input class="num_input" :adjust-position="false" v-model="state.price" type="digit" />
        </div>
      </div>

      <div class="bottom_box">
        <div @click="pay" class="btn_pay">立即支付</div>
      </div>
    </div>
  </s-layout>
</template>

<script setup>
import sheep from '@/sheep';
import { reactive, ref, nextTick, watch, computed } from 'vue';
import { onLoad, onShow, onUnload, onPageScroll, onPullDownRefresh } from '@dcloudio/uni-app';
const isLogin = computed(() => sheep.$store('user').isLogin);
import { showAuthModal } from '@/sheep/hooks/useModal';
import { queryToParams } from '@/sheep/helper/index.js';

let state = reactive({
  price: null,
  shop_name: '宁波天钧伯爵科技有限公司',
});

onLoad((options) => {

  if (options.q) {
    let query = queryToParams(decodeURIComponent(options.q).split('?')[1]);
    console.log(query);

    if (query.price) {
      state.price = query.price
    }

    if (query.shop_name) {
      state.shop_name = query.shop_name;
    }
  }

  // console.log(isLogin.value);

  if (!isLogin.value) {
    showAuthModal();
  }

  uni.onAppShow(function (show_date) {
    console.log(show_date);

    let payStatus = show_date.refererrInfo?.extraData?.payStatus;

    if (show_date.refererrInfo?.extraData) {
      if (payStatus == 1) {
        sheep.$router.go('/pages/merchant/pay_result', {
          order_sn: state.order_sn,
          price: state.price,
        });
        return;
      } else if (payStatus == 0) {
        uni.showToast({
          title: '支付失败',
          icon: 'none',
        });
        return;
      } else if (payStatus == 3) {
        uni.showToast({
          title: '已取消支付',
          icon: 'none',
        });
        return;
      }
    } else {
      if (show_date.scene !== 1038) {
        return
      }
      // 轮询支付
      let flg = 0;
      const maxAttempts = 3;
      const interval = setInterval(() => {
        if (flg >= maxAttempts) {
          clearInterval(interval);
          uni.showToast({
            title: '支付失败',
            icon: 'none',
          });
          return;
        }
        sheep.$api.pay.get_pre_order_status({
          pre_order: state.pre_order,
        }).then((res) => {
          console.log(res,"----", state.pre_order);
          if (res.data.status == 2) {
            clearInterval(interval);
            sheep.$router.go('/pages/merchant/pay_result', {
              order_sn: state.order_sn,
              price: state.price,
            });
          }
        });
        flg++;
      }, 1300);
    }
  });
});

async function pay() {
  // 校验支付金额格式
  if (!state.price || state.price <= 0) {
    uni.showToast({
      title: '请输入正确金额',
      icon: 'none',
      duration: 1500,
    });
    return;
  }

  if (state.price && state.price.toString().includes('.')) {
    // 验证小数点前后 最少一位
    if (
      state.price.toString().split('.')[0].length < 1 ||
      state.price.toString().split('.')[1].length < 1
    ) {
      uni.showToast({
        title: '金额格式不正确',
        icon: 'none',
        duration: 1500,
      });
      return;
    }
  }

  let price = Number(state.price);
  if (isNaN(price)) {
    uni.showToast({
      title: '请输入正确的金额',
      icon: 'none',
      duration: 1500,
    });
    return;
  }

  // 验证金额小数点位数
  if (price && price.toString().includes('.')) {
    const decimal = price.toString().split('.')[1];
    if (decimal && decimal.length > 2) {
      uni.showToast({
        title: '金额最多支持两位小数',
        icon: 'none',
        duration: 1500,
      });
      return;
    }
  }

  // 半屏支付

  let pre_res = await sheep.$api.pay.create_ls({ price, shop_name: state.shop_name });

  if (pre_res.error == 0) {
    const { pre_order: preOrderId, merchant_id: merchantId, third_order, amount } = pre_res.data;
    state.order_sn = third_order;
    state.pre_order = preOrderId;

    uni.openEmbeddedMiniProgram({
      appId: 'wx38a3350891b22014',
      path: `pages/plugin/pay?preOrderId=${preOrderId}&merchantId=${merchantId}`,
      extraData: {
        type: 1,
      },
      success(res) {
        // 打开成功
      },
    });
  }


  // 原小程序支付
  // let res = await sheep.$api.pay.create_order({ price, shop_name: state.shop_name });

  // if (res.error == 0) {
  //   let order_sn = res.data.order_sn;
  //   let payData = await sheep.$api.pay.shop_pay({
  //     payment: 'wechat',
  //     order_sn,
  //   });

  //   if (payData.error == -1) {
  //     sheep.$store('user').logout();
  //   }

  //   if (payData.error == 0) {
  //     uni.requestPayment({
  //       provider: 'wxpay',
  //       ...payData.data.pay_data,
  //       success: (pay_res) => {
  //         sheep.$router.go('/pages/merchant/pay_result', {
  //           order_sn,
  //           price: state.price,
  //         });
  //       },
  //       fail: (err) => {
  //         console.log(err);
  //       },
  //     });
  //   }
  // }
}


</script>

<style lang="less" scoped>
div,
view {
  box-sizing: border-box;
}

.page {
  width: 100vw;
  height: 100vh;
  position: relative;
}

.bgi {
  display: block;
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  z-index: -999;
}

.pay_box {
  position: relative;
  left: 25rpx;
  top: 30.5vh;
  z-index: 999;
  width: 700rpx;
  border-radius: 16rpx;
  padding: 50rpx 30rpx;
  background-color: #ffffff86;

  .title {
    text-align: center;
    font-size: 30rpx;
    font-weight: 700;
  }

  .num_box {
    margin-top: 50rpx;
    display: flex;
    padding-left: 180rpx;
    // border: 1px solid red;

    .ico {
      font-size: 56rpx;
      font-weight: 700;
      height: 80rpx;
      line-height: 85rpx;
    }

    .num_input {
      display: block;
      width: 270rpx;
      height: 80rpx;
      color: #f40;
      margin-left: 10rpx;
      font-size: 55rpx;
      font-weight: 700;
      // background-color: #141414;
      border-bottom: 2px solid #000000;
    }
  }
}

.bottom_box {
  position: absolute;
  top: 45vh;
  width: 100%;

  .btn_pay {
    text-align: center;
    color: #fff;
    // border-radius: 10rpx;
    width: 280rpx;
    font-weight: 700;
    font-size: 32rpx;
    margin: 100rpx auto 0;
    padding: 20rpx 15rpx;
    background-color: #bc3354;
    // background: linear-gradient(270deg, #003ad9 0%, #3dc8ff 100%);
  }
}

.tips {
  position: absolute;
  bottom: 18vh;
  width: 100%;
  text-align: center;
  font-weight: 700;
  color: #141414;
}
</style>
